<template>
  <div class="work-orders-management">
    <div class="page-header">
      <h2>报修工单管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建工单
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="待处理工单"
          :value="statistics.pendingCount"
          color="#ff4d4f"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="进行中工单"
          :value="statistics.processingCount"
          color="#1890ff"
          icon="ant-design:tool-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成工单"
          :value="statistics.completedCount"
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均处理时间"
          :value="statistics.avgProcessTime"
          suffix="小时"
          color="#faad14"
          icon="ant-design:field-time-outlined"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card :bordered="false" class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="房间号">
          <Input
            v-model:value="searchForm.roomNumber"
            placeholder="请输入房间号"
          />
        </FormItem>
        <FormItem label="报修类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择类型"
            style="width: 120px"
          >
            <SelectOption
              v-for="type in workOrderTypes"
              :key="type.value"
              :value="type.value"
            >
              {{ type.label }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="工单状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <SelectOption
              v-for="status in workOrderStatuses"
              :key="status.value"
              :value="status.value"
            >
              {{ status.label }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="紧急程度">
          <Select
            v-model:value="searchForm.priority"
            placeholder="请选择优先级"
            style="width: 120px"
          >
            <SelectOption value="low">一般</SelectOption>
            <SelectOption value="medium">紧急</SelectOption>
            <SelectOption value="high">非常紧急</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
        </FormItem>
        <FormItem>
          <Button @click="handleReset">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 工单列表 -->
    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredWorkOrders"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag>{{ getTypeText(record.type) }}</Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleAssign(record)"
              >
                分派
              </Button>
              <Button
                v-if="record.status === 'assigned'"
                type="link"
                size="small"
                @click="handleStart(record)"
              >
                开始
              </Button>
              <Button
                v-if="record.status === 'processing'"
                type="link"
                size="small"
                @click="handleComplete(record)"
              >
                完成
              </Button>
              <Button type="link" size="small" @click="handleEdit(record)">
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新建/编辑工单弹窗 -->
    <Modal
      v-model:open="showAddModal"
      :title="isEdit ? '编辑工单' : '新建工单'"
      width="600px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form
        ref="workOrderFormRef"
        :model="workOrderForm"
        :rules="workOrderRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="报修房间" name="roomNumber">
              <Select
                v-model:value="workOrderForm.roomNumber"
                placeholder="请选择房间"
                style="width: 100%"
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.roomNumber"
                >
                  {{ room.roomNumber }} ({{ room.tenantName }})
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="报修类型" name="type">
              <Select
                v-model:value="workOrderForm.type"
                placeholder="请选择报修类型"
                style="width: 100%"
              >
                <SelectOption
                  v-for="type in workOrderTypes"
                  :key="type.value"
                  :value="type.value"
                >
                  {{ type.label }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="报修描述" name="description">
          <Textarea
            v-model:value="workOrderForm.description"
            placeholder="请详细描述问题"
            :rows="3"
          />
        </FormItem>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="紧急程度" name="priority">
              <Select
                v-model:value="workOrderForm.priority"
                placeholder="请选择紧急程度"
                style="width: 100%"
              >
                <SelectOption value="low">一般</SelectOption>
                <SelectOption value="medium">紧急</SelectOption>
                <SelectOption value="high">非常紧急</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="联系电话" name="contactPhone">
              <Input
                v-model:value="workOrderForm.contactPhone"
                placeholder="请输入联系电话"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="workOrderForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 工单详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="工单详情"
      width="600px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="工单编号">
          {{ selectedWorkOrder?.id }}
        </DescriptionsItem>
        <DescriptionsItem label="房间号">
          {{ selectedWorkOrder?.roomNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="报修类型">
          <Tag>{{ getTypeText(selectedWorkOrder?.type) }}</Tag>
        </DescriptionsItem>
        <DescriptionsItem label="工单状态">
          <Tag :color="getStatusColor(selectedWorkOrder?.status)">
            {{ getStatusText(selectedWorkOrder?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="紧急程度">
          <Tag :color="getPriorityColor(selectedWorkOrder?.priority)">
            {{ getPriorityText(selectedWorkOrder?.priority) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedWorkOrder?.contactPhone }}
        </DescriptionsItem>
        <DescriptionsItem label="创建时间" :span="2">
          {{ formatDateTime(selectedWorkOrder?.createdAt) }}
        </DescriptionsItem>
        <DescriptionsItem label="报修描述" :span="2">
          {{ selectedWorkOrder?.description }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedWorkOrder?.remarks || '无' }}
        </DescriptionsItem>
        <DescriptionsItem v-if="selectedWorkOrder?.assignedTo" label="分派给">
          {{ selectedWorkOrder?.assignedTo }}
        </DescriptionsItem>
        <DescriptionsItem v-if="selectedWorkOrder?.assignedAt" label="分派时间">
          {{ formatDateTime(selectedWorkOrder?.assignedAt) }}
        </DescriptionsItem>
        <DescriptionsItem v-if="selectedWorkOrder?.startedAt" label="开始时间">
          {{ formatDateTime(selectedWorkOrder?.startedAt) }}
        </DescriptionsItem>
        <DescriptionsItem
          v-if="selectedWorkOrder?.completedAt"
          label="完成时间"
        >
          {{ formatDateTime(selectedWorkOrder?.completedAt) }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 分派工单弹窗 -->
    <Modal
      v-model:open="showAssignModal"
      title="分派工单"
      width="500px"
      @ok="handleAssignConfirm"
      @cancel="handleAssignCancel"
    >
      <Form :model="assignForm" layout="vertical">
        <FormItem label="分派给" name="assignedTo">
          <Select
            v-model:value="assignForm.assignedTo"
            placeholder="请选择维修人员"
            style="width: 100%"
          >
            <SelectOption
              v-for="worker in maintenanceWorkers"
              :key="worker.id"
              :value="worker.name"
            >
              {{ worker.name }} ({{ worker.specialty }})
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="分派说明" name="assignNote">
          <Textarea
            v-model:value="assignForm.assignNote"
            placeholder="请输入分派说明"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

// 工单状态枚举
enum WorkOrderStatus {
  PENDING = 'pending',
  ASSIGNED = 'assigned',
  PROCESSING = 'processing',
  COMPLETED = 'completed',
  CANCELLED = 'cancelled',
}

// 工单类型配置
const workOrderTypes = [
  { value: 'plumbing', label: '水电维修' },
  { value: 'electrical', label: '电器维修' },
  { value: 'furniture', label: '家具维修' },
  { value: 'appliance', label: '设备维修' },
  { value: 'other', label: '其他' },
];

// 工单状态配置
const workOrderStatuses = [
  { value: WorkOrderStatus.PENDING, label: '待处理' },
  { value: WorkOrderStatus.ASSIGNED, label: '已分派' },
  { value: WorkOrderStatus.PROCESSING, label: '进行中' },
  { value: WorkOrderStatus.COMPLETED, label: '已完成' },
  { value: WorkOrderStatus.CANCELLED, label: '已取消' },
];

// 响应式数据
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showAssignModal = ref(false);
const isEdit = ref(false);
const selectedWorkOrder = ref<any>(null);
const workOrderFormRef = ref();

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  type: undefined,
  status: undefined,
  priority: undefined,
});

// 工单表单
const workOrderForm = reactive({
  id: '',
  roomNumber: '',
  type: '',
  description: '',
  priority: 'medium',
  contactPhone: '',
  remarks: '',
});

// 分派表单
const assignForm = reactive({
  assignedTo: '',
  assignNote: '',
});

// 表单验证规则
const workOrderRules = {
  roomNumber: [{ required: true, message: '请选择房间' }],
  type: [{ required: true, message: '请选择报修类型' }],
  description: [{ required: true, message: '请填写报修描述' }],
  priority: [{ required: true, message: '请选择紧急程度' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 模拟数据
const workOrders = ref([
  {
    id: 'WO001',
    roomNumber: '101',
    tenantName: '张三',
    type: 'plumbing',
    description: '厨房水龙头漏水，需要维修',
    priority: 'medium',
    status: WorkOrderStatus.PENDING,
    contactPhone: '13800138001',
    remarks: '客户比较急，希望尽快处理',
    createdAt: dayjs('2024-01-15 10:00'),
    updatedAt: dayjs('2024-01-15 10:00'),
  },
  {
    id: 'WO002',
    roomNumber: '201',
    tenantName: '李四',
    type: 'electrical',
    description: '空调不制冷，需要检查维修',
    priority: 'high',
    status: WorkOrderStatus.ASSIGNED,
    contactPhone: '13800138002',
    remarks: '天气炎热，客户急需',
    assignedTo: '王师傅',
    assignedAt: dayjs('2024-01-15 11:00'),
    createdAt: dayjs('2024-01-15 09:30'),
    updatedAt: dayjs('2024-01-15 11:00'),
  },
  {
    id: 'WO003',
    roomNumber: '301',
    tenantName: '王五',
    type: 'furniture',
    description: '衣柜门把手松动，需要紧固',
    priority: 'low',
    status: WorkOrderStatus.COMPLETED,
    contactPhone: '13800138003',
    remarks: '已完成维修',
    assignedTo: '李师傅',
    assignedAt: dayjs('2024-01-14 14:00'),
    startedAt: dayjs('2024-01-14 15:00'),
    completedAt: dayjs('2024-01-14 16:00'),
    createdAt: dayjs('2024-01-14 13:00'),
    updatedAt: dayjs('2024-01-14 16:00'),
  },
]);

// 可用房间数据
const availableRooms = ref([
  { id: '101', roomNumber: '101', tenantName: '张三' },
  { id: '102', roomNumber: '102', tenantName: '李四' },
  { id: '201', roomNumber: '201', tenantName: '王五' },
  { id: '202', roomNumber: '202', tenantName: '赵六' },
  { id: '301', roomNumber: '301', tenantName: '孙七' },
]);

// 维修人员数据
const maintenanceWorkers = ref([
  { id: '1', name: '王师傅', specialty: '水电维修' },
  { id: '2', name: '李师傅', specialty: '电器维修' },
  { id: '3', name: '张师傅', specialty: '家具维修' },
  { id: '4', name: '刘师傅', specialty: '综合维修' },
]);

// 统计信息
const statistics = computed(() => {
  const pendingCount = workOrders.value.filter(
    (item) => item.status === WorkOrderStatus.PENDING,
  ).length;
  const processingCount = workOrders.value.filter(
    (item) => item.status === WorkOrderStatus.PROCESSING,
  ).length;
  const completedCount = workOrders.value.filter(
    (item) => item.status === WorkOrderStatus.COMPLETED,
  ).length;

  // 计算平均处理时间（简化计算）
  const completedOrders = workOrders.value.filter(
    (item) => item.status === WorkOrderStatus.COMPLETED && item.completedAt,
  );
  const avgProcessTime = completedOrders.length > 0 ? 4.5 : 0;

  return {
    pendingCount,
    processingCount,
    completedCount,
    avgProcessTime,
  };
});

// 过滤后的工单列表
const filteredWorkOrders = computed(() => {
  let filtered = workOrders.value;

  if (searchForm.roomNumber) {
    filtered = filtered.filter((item) =>
      item.roomNumber.includes(searchForm.roomNumber),
    );
  }

  if (searchForm.type) {
    filtered = filtered.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    filtered = filtered.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.priority) {
    filtered = filtered.filter((item) => item.priority === searchForm.priority);
  }

  return filtered;
});

// 表格列定义
const columns = [
  {
    title: '工单编号',
    dataIndex: 'id',
    key: 'id',
    width: 100,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '报修类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '报修描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
    ellipsis: true,
  },
  {
    title: '紧急程度',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '工单状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 160,
    customRender: ({ text }: any) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 工具函数
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [WorkOrderStatus.PENDING]: 'orange',
    [WorkOrderStatus.ASSIGNED]: 'blue',
    [WorkOrderStatus.PROCESSING]: 'processing',
    [WorkOrderStatus.COMPLETED]: 'success',
    [WorkOrderStatus.CANCELLED]: 'default',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusItem = workOrderStatuses.find((item) => item.value === status);
  return statusItem?.label || status;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    low: 'default',
    medium: 'orange',
    high: 'red',
  };
  return colorMap[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: '一般',
    medium: '紧急',
    high: '非常紧急',
  };
  return priorityMap[priority] || priority;
};

const getTypeText = (type: string) => {
  const typeItem = workOrderTypes.find((item) => item.value === type);
  return typeItem?.label || type;
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';datetimedayjs.formatdatetimedayjs.format
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
};

const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    type: undefined,
    status: undefined,
    priority: undefined,
  });
  pagination.current = 1;
};

const handleView = (record: any) => {
  selectedWorkOrder.value = record;
  showDetailModal.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  Object.assign(workOrderForm, {
    ...record,
  });
  showAddModal.value = true;
};

const handleAssign = (record: any) => {
  selectedWorkOrder.value = record;
  showAssignModal.value = true;
};

const handleAssignConfirm = () => {
  if (!assignForm.assignedTo) {
    message.error('请选择维修人员');
    return;
  }

  const index = workOrders.value.findIndex(
    (item) => item.id === selectedWorkOrder.value.id,
  );
  if (index !== -1) {
    workOrders.value[index].status = WorkOrderStatus.ASSIGNED;
    workOrders.value[index].assignedTo = assignForm.assignedTo;
    workOrders.value[index].assignedAt = dayjs();
    workOrders.value[index].updatedAt = dayjs();
    message.success('工单分派成功');
    showAssignModal.value = false;
    handleAssignCancel();
  }
};

const handleAssignCancel = () => {
  Object.assign(assignForm, {
    assignedTo: '',
    assignNote: '',
  });
};

const handleStart = (record: any) => {
  Modal.confirm({
    title: '开始维修',
    content: `确定要开始维修房间 ${record.roomNumber} 的工单吗？`,
    onOk: () => {
      const index = workOrders.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        workOrders.value[index].status = WorkOrderStatus.PROCESSING;
        workOrders.value[index].startedAt = dayjs();
        workOrders.value[index].updatedAt = dayjs();
        message.success('维修已开始');
      }
    },
  });
};

const handleComplete = (record: any) => {
  Modal.confirm({
    title: '完成维修',
    content: `确定要完成房间 ${record.roomNumber} 的维修工单吗？`,
    onOk: () => {
      const index = workOrders.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        workOrders.value[index].status = WorkOrderStatus.COMPLETED;
        workOrders.value[index].completedAt = dayjs();
        workOrders.value[index].updatedAt = dayjs();
        message.success('维修已完成');
      }
    },
  });
};

const handleDelete = (record: any) => {
  Modal.confirm({
    title: '删除工单',
    content: `确定要删除房间 ${record.roomNumber} 的工单吗？`,
    onOk: () => {
      const index = workOrders.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        workOrders.value.splice(index, 1);
        message.success('删除成功');
      }
    },
  });
};

const handleSave = async () => {
  try {
    await workOrderFormRef.value.validate();

    if (isEdit.value) {
      // 编辑模式
      const index = workOrders.value.findIndex(
        (item) => item.id === workOrderForm.id,
      );
      if (index !== -1) {
        workOrders.value[index] = {
          ...workOrders.value[index],
          ...workOrderForm,
          updatedAt: dayjs(),...workOrderForm,
        };
        message.success('编辑成功');
      }
    } else {
      // 新增模式
      const newWorkOrder = {
        ...workOrderForm,
        id: `WO${Date.now().toString().slice(-6)}`,
        status: WorkOrderStatus.PENDING,
        createdAt: dayjs(),
        updatedAt: dayjs(),
      };
      workOrders.value.unshift(newWorkOrder);
      message.success('工单创建成功');
    }

    handleCancel();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  isEdit.value = false;
  workOrderFormRef.value?.resetFields();
  Object.assign(workOrderForm, {
    id: '',
    roomNumber: '',
    type: '',
    description: '',
    priority: 'medium',
    contactPhone: '',
    remarks: '',
  });
};

// 初始化
onMounted(() => {
  console.log('报修工单管理页面已加载');
});
</script>

<style scoped>
.work-orders-management {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}
</style>
